package org.dicr.util.jds;

import com.borland.dx.dataset.*;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author not attributable
 * @version 1.0
 */

public class RowIdGenerator extends EditAdapter {
	private static int counter = 0;

	/**
	 * Constructor
	 * 
	 * @param ds dataset
	 */
	public RowIdGenerator(StorageDataSet ds) {
		ds.addEditListener(this);
	}

	/**
	 * Generate key
	 * 
	 * @return generated key
	 */
	public static long getKey() {
		counter = ((counter + 1) % 1000);
		return System.currentTimeMillis() * 1000 + counter;
	}

	/**
	 * Search column which is row ID
	 * 
	 * @param row row to search
	 * @return column which is row ID or null
	 */
	public static Column findRowID(ReadRow row) {
		if (row == null) { throw new IllegalArgumentException("NULL row"); }
		Column[] cols = row.getColumns();
		for (int i = 0; i < cols.length; i++) {
			Column col = cols[i];
			if (col.isRowId() && col.getDataType() == Variant.LONG) { return col; }
		}
		return null;
	}

	/**
	 * @see com.borland.dx.dataset.EditAdapter#adding(com.borland.dx.dataset.DataSet,
	 *      com.borland.dx.dataset.ReadWriteRow)
	 */
	@Override
	public void adding(DataSet ds, ReadWriteRow row) {
		Column col = findRowID(ds);
		row.setLong(col.getOrdinal(), getKey());
	}
}
